
let currentPage = 1;
let pageSize = 10;
let totalPages = 1;
let totalCount = 0; // 添加总数变量
let allCourses = [];
let filteredCourses = [];
let currentEditingCourseId = null;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    initializePage();
});

// 初始化页面
function initializePage() {
    loadCourses();
    bindEvents();
}

function bindEvents() {
    document.getElementById('searchInput').addEventListener('input', debounce(filterCourses, 300));

    document.getElementById('creditsFilter').addEventListener('change', filterCourses);

    document.getElementById('addCourseForm').addEventListener('submit', handleAddCourse);
    document.getElementById('editCourseForm').addEventListener('submit', handleEditCourse);

    document.getElementById('confirmDeleteBtn').addEventListener('click', handleDeleteCourse);

    document.getElementById('addCourseModal').addEventListener('hidden.bs.modal', resetAddForm);
    document.getElementById('editCourseModal').addEventListener('hidden.bs.modal', resetEditForm);
}

// 加载课程数据
async function loadCourses() {
    showLoading();

    try {

        const params = new URLSearchParams({
            page: currentPage,
            page_size: pageSize
        });

        const searchTerm = document.getElementById('searchInput').value.trim();
        if (searchTerm) {
            params.append('search', searchTerm);
        }

        // 添加学分筛选
        const creditsFilter = document.getElementById('creditsFilter').value;
        if (creditsFilter) {
            params.append('credits', creditsFilter);
        }

        const response = await fetch(`/api/courses?${params}`);
        const result = await response.json();

        if (result.success) {
            const data = result.data;
            allCourses = data.items;
            filteredCourses = [...allCourses];

            totalPages = data.pagination.total_pages;
            currentPage = data.pagination.current_page;
            totalCount = data.pagination.total_count;

            displayCourses();
        } else {
            console.error('加载课程数据失败:', result.msg, result.error);
            showError('加载失败：' + result.msg + (result.error ? ' - ' + result.error : ''));
            showEmptyState();
        }
    } catch (error) {
        console.error('加载课程数据出错:', error);
        showError('加载失败：网络错误');
        displayCourses();
    }
}

// 显示加载状态
function showLoading() {
    document.getElementById('loadingSpinner').style.display = 'block';
    document.getElementById('courseTableContainer').style.display = 'none';
    document.getElementById('emptyState').style.display = 'none';
}

// 显示空状态
function showEmptyState() {
    document.getElementById('loadingSpinner').style.display = 'none';
    document.getElementById('courseTableContainer').style.display = 'none';
    document.getElementById('emptyState').style.display = 'block';
    updateCourseCount(0);
}

// 显示课程列表
function displayCourses() {
    document.getElementById('loadingSpinner').style.display = 'none';

    if (filteredCourses.length === 0) {
        showEmptyState();
        return;
    }

    document.getElementById('courseTableContainer').style.display = 'block';
    document.getElementById('emptyState').style.display = 'none';

    // 直接渲染当前页数据（已经是分页后的数据）
    renderCourseTable(filteredCourses);
    renderPagination();
    updateCourseCount(totalCount); // 显示总数而不是当前页数量
}

// 渲染课程表格
function renderCourseTable(courses) {
    const tbody = document.getElementById('courseTableBody');
    tbody.innerHTML = '';
    
    courses.forEach(course => {
        const row = document.createElement('tr');
        row.className = 'fade-in';
        row.innerHTML = `
            <td>${course.id}</td>
            <td><strong>${course.name}</strong></td>
            <td><code>${course.code}</code></td>
            <td><span class="badge bg-primary">${course.credits}</span></td>
            <td>
                <span class="course-description" title="${course.description || ''}">
                    ${course.description || '暂无描述'}
                </span>
            </td>
            <td>${formatDateTime(course.created_time)}</td>
            <td>
                <div class="btn-group" role="group">
                    <button type="button" class="btn btn-outline-primary btn-sm"
                            onclick="editCourse(${course.id})" title="编辑">
                        <i class="fas fa-edit"></i>
                        编辑
                    </button>
                    <button type="button" class="btn btn-outline-danger btn-sm"
                            onclick="deleteCourse(${course.id}, '${course.name}')" title="删除">
                        <i class="fas fa-trash"></i>
                        删除
                    </button>
                </div>
            </td>
        `;
        tbody.appendChild(row);
    });
}

// 渲染分页
function renderPagination() {
    const pagination = document.getElementById('pagination');
    pagination.innerHTML = '';
    
    if (totalPages <= 1) return;
    
    // 上一页按钮
    const prevLi = document.createElement('li');
    prevLi.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
    prevLi.innerHTML = `
        <a class="page-link" href="#" onclick="changePage(${currentPage - 1})">
            <i class="fas fa-chevron-left"></i>
            上一页
        </a>
    `;
    pagination.appendChild(prevLi);
    
    // 页码按钮
    for (let i = 1; i <= totalPages; i++) {
        if (i === 1 || i === totalPages || (i >= currentPage - 2 && i <= currentPage + 2)) {
            const li = document.createElement('li');
            li.className = `page-item ${i === currentPage ? 'active' : ''}`;
            li.innerHTML = `<a class="page-link" href="#" onclick="changePage(${i})">${i}</a>`;
            pagination.appendChild(li);
        } else if (i === currentPage - 3 || i === currentPage + 3) {
            const li = document.createElement('li');
            li.className = 'page-item disabled';
            li.innerHTML = '<span class="page-link">...</span>';
            pagination.appendChild(li);
        }
    }
    
    // 下一页按钮
    const nextLi = document.createElement('li');
    nextLi.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
    nextLi.innerHTML = `
        <a class="page-link" href="#" onclick="changePage(${currentPage + 1})">
            <i class="fas fa-chevron-right"></i>
            下一页
        </a>
    `;
    pagination.appendChild(nextLi);
}

// 更新课程数量显示
function updateCourseCount(count) {
    document.getElementById('listCount').textContent = count;
}


// 切换页面
function changePage(page) {
    if (page < 1 || page > totalPages || page === currentPage) return;
    currentPage = page;
    loadCourses(); // 重新加载数据
}

// 筛选课程
function filterCourses() {
    currentPage = 1; // 重置到第一页
    loadCourses(); // 重新加载数据
}

// 重置筛选器
function resetFilters() {
    document.getElementById('searchInput').value = '';
    document.getElementById('creditsFilter').value = '';
    currentPage = 1;
    loadCourses(); // 重新加载数据
}

// 处理添加课程
async function handleAddCourse(event) {
    event.preventDefault();

    const form = event.target;
    if (!form.checkValidity()) {
        form.classList.add('was-validated');
        return;
    }

    const formData = new FormData(form);
    const courseData = {
        name: formData.get('name'),
        code: formData.get('code'),
        credits: parseFloat(formData.get('credits')),
        description: formData.get('description')
    };

    try {
        const response = await fetch('/api/courses', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(courseData)
        });

        const result = await response.json();

        if (result.success) {
            // 添加成功
            showSuccess(result.msg);
            bootstrap.Modal.getInstance(document.getElementById('addCourseModal')).hide();
            resetAddForm(); // 重置表单
            loadCourses(); // 重新加载课程列表
        } else {
            // 添加失败
            showError(result.msg + (result.error ? ' - ' + result.error : ''));
        }
    } catch (error) {
        console.error('添加课程出错:', error);
        showError('添加失败：网络错误');
    }
}

// 编辑课程
function editCourse(courseId) {
    const course = allCourses.find(c => c.id === courseId);
    if (!course) {
        showError('课程不存在');
        return;
    }

    currentEditingCourseId = courseId;

    // 填充编辑表单
    document.getElementById('editCourseId').value = course.id;
    document.getElementById('editCourseName').value = course.name;
    document.getElementById('editCourseCode').value = course.code;
    document.getElementById('editCourseCredits').value = course.credits;
    document.getElementById('editCourseDescription').value = course.description || '';

    
    new bootstrap.Modal(document.getElementById('editCourseModal')).show();
}

// 处理编辑课程
async function handleEditCourse(event) {
    event.preventDefault();

    const form = event.target;
    if (!form.checkValidity()) {
        form.classList.add('was-validated');
        return;
    }

    const formData = new FormData(form);
    const courseData = {
        id: parseInt(formData.get('id')),
        name: formData.get('name'),
        code: formData.get('code'),
        credits: parseFloat(formData.get('credits')),
        description: formData.get('description')
    };

    try {
        const response = await fetch(`/api/courses/${courseData.id}`, {
            method: 'PUT',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(courseData)
        });

        const result = await response.json();

        if (result.success) {
            showSuccess(result.msg);
            bootstrap.Modal.getInstance(document.getElementById('editCourseModal')).hide();
            resetEditForm(); // 重置表单
            loadCourses(); 
        } else {
            showError(result.msg + (result.error ? ' - ' + result.error : ''));
        }
    } catch (error) {
        console.error('更新课程出错:', error);
        showError('更新失败：网络错误');
    }
}

// 删除课程
function deleteCourse(courseId, courseName) {
    currentEditingCourseId = courseId;
    document.getElementById('deleteCourseInfo').textContent = courseName;
    new bootstrap.Modal(document.getElementById('deleteCourseModal')).show();
}

// 处理删除课程
async function handleDeleteCourse() {
    if (!currentEditingCourseId) return;

    try {
        const response = await fetch(`/api/courses/${currentEditingCourseId}`, {
            method: 'DELETE'
        });

        const result = await response.json();

        if (result.success) {
            // 删除成功
            showSuccess(result.msg);
            bootstrap.Modal.getInstance(document.getElementById('deleteCourseModal')).hide();
            currentEditingCourseId = null; // 重置当前编辑ID
            loadCourses(); // 重新加载课程列表
        } else {
            // 删除失败
            showError(result.msg + (result.error ? ' - ' + result.error : ''));
        }
    } catch (error) {
        console.error('删除课程出错:', error);
        showError('删除失败：网络错误');
    }
}

// 重置添加表单
function resetAddForm() {
    const form = document.getElementById('addCourseForm');
    form.reset();
    form.classList.remove('was-validated');
}

// 重置编辑表单
function resetEditForm() {
    const form = document.getElementById('editCourseForm');
    form.reset();
    form.classList.remove('was-validated');
    currentEditingCourseId = null;
}
